<?php
class EventsController extends AppController
{
    var $name = 'Events';
    var $helpers = array
	(
        'Html', 'Form'
    );
    var $uses = array('Event','User', 'EventType', 'Season','UserType', 'EventAttendee', 'EventPrivilage');

	function beforeFilter(){ 
        $this->__validateLoginStatus();
    }

    function __validateLoginStatus(){ 
       if($this->Session->check('User') == false){
          $this->Session->setFlash('you must be logged in to access this page');
          $this->redirect(array('controller' => 'users', 'action' => 'login'));
       }
    }
    
    function index()
    {
    	$accessArray = $this->Session->read('accessArray');
    	if (!$accessArray['AdminAccess']) {
    		$this->Session->setFlash('You are not allowed to access this page');
    		$this->redirect(array('controller' => HOME_CONTROLLER, 'action' => 'index'));
    	}
        $this->Event->recursive = 0;
        $this->set('events', $this->paginate());
    }

    function view($id = null)
    {	
    	//check the privilage of viewing this event
        if (!$id)
        {
            $this->Session->setFlash(__('Invalid Event', true));
            $this->redirect(array(
                'action'=>'index'
            ));
        }
        
        $this->__eventPrivilageParser('view', $id);
        
    	$event = $this->Event->find('first', array(
    									'conditions' => array(
    										'Event.id' => $id
    									),
    									'recursive' => -1
    								)
    							);
    	if (!$event) {
    		$this->redirect(array('controller' => HOME_CONTROLLER, 'action' => 'index'));
    	}
    	$comment = $this->requestAction('/comments/load_comments/'.$id);
    	
    	$season_name = $this->Season->find('first', array(
    										'condidtions' => array('Season.id' => $event['Event']['season_id']),
    										'fields' => array('Season.season_name'), 
    										'recursive' => -1
    									));
    									
    	$event_type_name = $this->EventType->find('first', array(
    										'conditions' => array('EventType.id' => $event['Event']['event_type_id']),
    										'fields' => array('EventType.title'),
    										'recursive' => -1
    									));
    									
    	$this->set('eventType', $event_type_name);
    	$this->set('season', $season_name);
        $this->set('comment', $comment);
        $this->set('event', $event);
        $this->set('accessArray', $this->Session->read('accessArray'));
        $this->set('user_id',$this->Session->read('User.id'));
    }
    
    function main($id = null, $allow = null) {
    	if (!$id) {
    		$this->Session->setFlash(__('Invalid Event', true));
    		$this->redirect(array ('action' => 'index'));
    	}
    	
    	$this->__eventPrivilageParser('main', $id);
    	
    	$event = $this->Event->find('first', array('conditions' => array('Event.id' => $id), 'recursive'=>-1));
    	$user_id = $this->Session->read('User.id');
    	if (!$event) {
    		$this->Session->setFlash(__('Invalid Event', true));
    		$this->redirect(array('controller' => HOME_CONTROLLER, 'action' => 'index'));
    	}

    	//case of access the main page for the first time not from the content page
    	$attendees = $this->EventAttendee->find('first', 
	    									array('conditions' => array(
	    									'EventAttendee.user_id' => $user_id, 
	    									'EventAttendee.event_id' => $id),
	    									'recursive' => -1
	    									));;
    	if (!$allow) {
	    	if ($attendees) {
	    		$this->redirect(array('action' => 'view', $id));
	    	}
    	}
    	
    	$season_name = $this->Season->find('first', array(
    										'condidtions' => array('Season.id' => $event['Event']['season_id']),
    										'fields' => array('Season.season_name'), 
    										'recursive' => -1
    									));
    									
    	$event_type_name = $this->EventType->find('first', array(
    										'conditions' => array('EventType.id' => $event['Event']['event_type_id']),
    										'fields' => array('EventType.title'),
    										'recursive' => -1
    									));
    									
    	$this->set('eventType', $event_type_name);
    	$this->set('season', $season_name);
    	$this->set('event', $event);
    	$this->set('attendee', $attendees);
    	$this->set('user_id', $user_id);
    	$this->set('accessArray', $this->Session->read('accessArray'));
    }
    
    function __eventPrivilageParser($action, $event_id) {
		//check that this user have privilage accessing this page
        $user_id = $this->Session->read('User.id');
        $user_type_id = $this->Session->read('User.user_type_id');
        $event_privilage = $this->EventPrivilage->find('first', array(
        													'conditions' => array(
        															'EventPrivilage.event_id' => $event_id,
        															'EventPrivilage.user_type_id' => $user_type_id 
        															),
        													'recursive' => -1
        														)
        													);
        if (!$event_privilage) {
        	$this->Session->setFlash(__('You don\'t have the privialge to access this page', true));
        	$this->redirect(array('controller' => HOME_CONTROLLER, 'action' => 'index'));
        }
        else {
        	$accessStr = $event_privilage['EventPrivilage']['privilage'];
        	if ($accessStr{$this->__getActionValue($action)} == '0') {
        		$this->Session->setFlash(__('You don\'t have the privialge to access this page', true));
        		$this->redirect(array('controller' => HOME_CONTROLLER, 'action' => 'index'));
        	}
        }
    	
    }
    
    function __getActionValue($action) {
    	switch ($action) {
    		case "view":
    			return 0;
    		case "main":
    			return 0;
    		case "edit":
    			return 1;
    	}
    }
	
	function __loadCreateEventData(){
		//loading all the organizers to be used in the attendance manager
		$organizers = $this->User->find('all', array('conditions' => array('User.user_type_id' => 3),
					'fields' => array('User.id', 'User.first_name', 'User.last_name'),
					'order' => array ('User.first_name', 'User.last_name ASC'),
					'recursive' => -1
					));
		$returnOrganizers = array();
		foreach ($organizers as $organizer) {
			$organizer = $organizer['User'];
			$returnOrganizers[$organizer['id']] = $organizer['first_name'] . ' ' . $organizer['last_name'];
		}
		$this->set('organizers', $returnOrganizers);
		
		//loading the instructors
		$instructors = $this->User->find('list', array('fields'=>'username','recursive'=>-1));
		$this->set('instructors', $instructors);
		
		//loading the event types
		$eventTypes = $this->EventType->find('all', array('order' => array('EventType.title ASC')));
		$selectEvents = array();
		$eventTypesBodies = array();
		foreach ($eventTypes as $eventType) {
			$eventType = $eventType['EventType'];
			$selectEvents[$eventType['id']] = $eventType['title'];
			$eventTypesBodies[$eventType['id']] = $eventType['body_template'];				
		}
		
		$this->set('selectEvents', $selectEvents);
		$this->set('eventTypesBodies', $eventTypesBodies);
		
		//loading current season
		$season = $this->Season->find('all', array(
				'conditions' => array('CURDATE() BETWEEN Season.start_date AND Season.end_date')
			));
		
		$this->set('season_id', $season[0]['Season']['id']);
		
		//loading the user types
		$user_types = $this->UserType->find('all',array('order'=>'id','recursive'=>-1));
		$this->set('user_types', $user_types);
				
	}
	
    function add(){
    	$this->__mainValidate('CreateEvent');
        if (!empty($this->data)){
        
            $this->Event->create();

            //construct the privilege string
            $privilege = '';
            foreach ($this->data['EventPrivilage'] as &$userType){
                $privilege = '';
                if (empty($userType['privilage'])){
                    $privilege = $userType['privilage-view'];
                    $privilege = $privilege.$userType['privilage-edit'];
                    unset($userType['privilage-view']);
                    unset($userType['privilage-edit']);
                    $userType['privilage'] = $privilege;
                }                    
            }
            
            //copy the privileges of the organizer to registration manager
            //assuming that registration manager have id of 3 and organizer have id = 4
            $this->data['EventPrivilage'][2]['privilage']=$this->data['EventPrivilage'][3]['privilage'];
                                    
            if ($this->Event->saveAll($this->data)){	
                $this->Session->setFlash(__('The Event has been saved', true));
                $this->redirect(array(
                    'action'=>'index'
                ));
            }else{
                $this->Session->setFlash(__('The Event could not be saved. Please, try again.', true));
            }
        }
		//setting the creator_id value to be used in the view
		$this->set('creator_id', $this->Session->read('User.id'));
		
		$this->__loadCreateEventData();

    }
    
    function edit($id = null)
    {
        if (!$id && empty($this->data)){
            $this->Session->setFlash(__('Invalid Event', true));
            $this->redirect(array('action'=>'index'));
        }
        $this->__eventPrivilageParser('edit', $id);
        if (! empty($this->data)){
                  
            //construct the privilege string
            $privilege = '';
            foreach ($this->data['EventPrivilage'] as &$userType){
                $privilege = '';
                if (empty($userType['privilage'])){
                    if (empty($userType['privilage-view']))
                        $privilege = '0';
                    else
                        $privilege = (bool)$userType['privilage-view'];

                    if (empty($userType['privilage-edit']))
                        $privilege = $privilege.'0';
                    else                                                            
                        $privilege = $privilege.((bool)$userType['privilage-edit']);                        
                    unset($userType['privilage-view']);
                    unset($userType['privilage-edit']);
                    $userType['privilage'] = $privilege;
                }                    
            }
        
            if ($this->Event->saveAll($this->data)){
                $this->Session->setFlash(__('The Event has been saved', true));
                $this->redirect(array(
                    'action'=>'index'
                ));
            }else{
                $this->Session->setFlash(__('The Event could not be saved. Please, try again.', true));
            }
        }
   		$this->__loadCreateEventData();
        $this->data = $this->Event->read(null, $id);
    }
    
    function delete($id = null, $season_id = null)
    {
        if (!$id || !$season_id)
        {
            $this->Session->setFlash(__('Invalid id for Event', true));
            $this->redirect(array(
                'action'=>'index'
            ));
        }
        if ($this->Event->del($id))
        {
            $this->Session->setFlash(__('Event deleted', true));
            $this->redirect(array(
                'controller' => 'seasons', 'action'=>'view', $season_id
            ));
        }
        $this->Session->setFlash(__('The Event could not be deleted. Please, try again.', true));
        $this->redirect(array(
            'controller' => 'seasons', 'action'=>'view', $season_id
        ));
    }
    
    function register($event_id = null){
    	if(!$event_id){
    		$this->Session->setFlash(__('Invalid event id',true));
    		$this->redirect(array('controller'=>HOME_CONTROLLER , 'action'=>'index'));
    	}
    	$attending = array('user_id'=>$this->Session->read('User.id'),'event_id'=>$event_id);
    	$this->EventAttendee->create();
    	$this->EventAttendee->save($attending);
    	$this->Session->setFlash(__('You have successfully registered',true));
    	$this->redirect(array('action'=>'main',$event_id));
    	return;
    }
    
    function close($event_id = null){
    	if(!$event_id){
    		$this->Session->setFlash(__('Invalid event id',true));
    		$this->redirect(array('controller'=>HOME_CONTROLLER , 'action'=>'index'));
    	}
    	$event = $this->Event->find('first',array('conditions'=>array('Event.id' => $event_id),'recursive' => -1));
    	$event['Event']['is_closed'] = 1;
    	$this->Event->save($event);
    	$this->redirect(array('action'=>'main',$event_id,1));
    	return;
    }
    
    function open($event_id = null){
    	if(!$event_id){
    		$this->Session->setFlash(__('Invalid event id',true));
    		$this->redirect(array('controller'=>HOME_CONTROLLER , 'action'=>'index'));
    	}
    	$event = $this->Event->find('first',array('conditions'=>array('Event.id' => $event_id),'recursive' => -1));
    	$event['Event']['is_closed'] = 0;
    	$this->Event->save($event);
    	$this->redirect(array('action'=>'main',$event_id,1));
    	return;
    }
}
?>
